package com.accountant.travelaccountant;

import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ChooseAccount2 extends Activity {

	TextView OpenAccount, openAccountstatistics, deleteAccount, EditAccount,
			RenameAccount, textviewinsideListview, checkboxinsideListview;
	DatabaseOperations_NonActivity databaseOperations;
	ArrayList<String> titles;
	EditText input;
	ListView listViewForShowingAccountNames;
	ChooseAccount2_ListViewAdapter listViewAdapterForChooseAccount2;

	/* For putting the buttons in the gridview just above the bottom gridview */
	GridView gridViewTop, gridViewBottom;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.choose_account2);
		/*
		 * For putting the buttons in the gridview just above the bottom
		 * gridview
		 */
		gridViewTop = (GridView) findViewById(R.id.gridViewForButtonsToPlaceAtTheTopOfTheBottom);
		/*
		 * Creating an object so that that object has the texts for the buttons
		 */
		ChooseAccount2_GridviewAboveBottom firstGridViewabovebottom = new ChooseAccount2_GridviewAboveBottom(
				this, this);
		gridViewTop.setAdapter(firstGridViewabovebottom);
		/* Function to give backgroung coloyr to gridview */
		HelperClassForActivities.addColourToGridView(gridViewTop, this);

		/* For putting the buttons in the last gridview */
		gridViewBottom = (GridView) findViewById(R.id.gridViewForButtonsToPlaceAtTheBottom);
		/* Creating an object so that that object has the texts for the buttons */
		ChooseAccount2_GridviewBottom firstGridViewatThebottom = new ChooseAccount2_GridviewBottom(
				this, this);
		gridViewBottom.setAdapter(firstGridViewatThebottom);
		/* Function to give backgroung coloyr to gridview */
		HelperClassForActivities.addColourToGridView(gridViewBottom, this);

		/* To create an object of titles */
		titles = new ArrayList<String>();

		/* Creating object to access its methods */
		databaseOperations = new DatabaseOperations_NonActivity(
				getApplicationContext());

		/* Code to open the database */
		databaseOperations.openWriteableDatabase();

		/* Code to get all the accounts from the database */
		titles = databaseOperations.retrieveAll(DatabaseOperations_NonActivity
				.getAmounttable(),
				new String[] { DatabaseOperations_NonActivity
						.getAmounttabletitle() }, null, null, null, null, null);

		/* Code to close the database */
		databaseOperations.closeDatabase();

		if (titles.size() == 0) {
			Toast.makeText(getApplicationContext(), "No Account to open",
					Toast.LENGTH_SHORT).show();
			finish();
		}
		/********************************************************************************/
		/* Working with the listview */
		listViewForShowingAccountNames = (ListView) findViewById(R.id.listViewforStoringAccountNames);
		listViewAdapterForChooseAccount2 = new ChooseAccount2_ListViewAdapter(
				ChooseAccount2.this, titles);
		listViewForShowingAccountNames
				.setAdapter(listViewAdapterForChooseAccount2);

		ChooseAccount2_ListViewAdapter.setTextOfSelectedTextview(null);
		/********************************************************************************/

	}

	/* Dialog box for Renaming a member */
	private void showDialogBoxRenameAccount(String title, String message) {

		/* Creating object to access its methods */
		databaseOperations = new DatabaseOperations_NonActivity(
				getApplicationContext());

		/* Firstly we create an object of AlertDialog.Builder */
		AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
		/* Now we initialise its contents */
		dialogBuilder.setTitle(title);
		dialogBuilder.setMessage(message);

		input = new EditText(this);
		input.setSingleLine();
		input.setText(ChooseAccount2_ListViewAdapter
				.getTextOfSelectedTextview());
		/* Function to put the cursor at the last */
		Utils_NotActivity.setCursorPosition(input);
		dialogBuilder.setView(input);

		/* Adding a event for changing text */
		input.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				Utils_NotActivity.validateTextLength(input);
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});

		dialogBuilder.setPositiveButton("Rename",
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {

						/* Inserting the record */
						databaseOperations.openWriteableDatabase();

						/*
						 * Validation for checking if the renamed account is
						 * there or not
						 */
						if (databaseOperations.retrieve(
								DatabaseOperations_NonActivity.getAmounttable(),
								new String[] { DatabaseOperations_NonActivity
										.getAmounttabletitle() },
								DatabaseOperations_NonActivity
										.getAmounttabletitle()
										+ "=\""
										+ input.getText().toString()
												.replaceAll("\\s+", " ").trim()
										+ "\"", null, null, null, null) != null) {
							Toast.makeText(getApplicationContext(),
									"Unable to rename, account already exists",
									Toast.LENGTH_SHORT).show();
							databaseOperations.closeDatabase();
							return;
						}

						/*
						 * Renaming the title in the amount table and that will
						 * cascade everywhere as it is having on update cascade
						 * constraint
						 */
						/* Pop up to say that account was renamed */
						Toast.makeText(
								getApplicationContext(),
								ChooseAccount2_ListViewAdapter
										.getTextOfSelectedTextview()
										+ " was renamed to "
										+ input.getText().toString()
												.replaceAll("\\s+", " ").trim(),
								Toast.LENGTH_SHORT).show();

						databaseOperations.updateRow(
								DatabaseOperations_NonActivity.getAmounttable(),
								DatabaseOperations_NonActivity
										.getAmounttabletitle(),
								input.getText().toString()
										.replaceAll("\\s+", " ").trim(),
								DatabaseOperations_NonActivity
										.getAmounttabletitle()
										+ "=\""
										+ ChooseAccount2_ListViewAdapter
												.getTextOfSelectedTextview()
										+ "\"", null);

						/* Code to get all the accounts from the database */
						titles = databaseOperations.retrieveAll(
								DatabaseOperations_NonActivity.getAmounttable(),
								new String[] { DatabaseOperations_NonActivity
										.getAmounttabletitle() }, null, null,
								null, null, null);

						/* Initializing the adapter */
						listViewAdapterForChooseAccount2 = new ChooseAccount2_ListViewAdapter(
								ChooseAccount2.this, titles);
						listViewForShowingAccountNames
								.setAdapter(listViewAdapterForChooseAccount2);
						ChooseAccount2_ListViewAdapter
								.setTextOfSelectedTextview(null);
						/* Closing the database */
						databaseOperations.closeDatabase();
					}
				});

		dialogBuilder.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						return;
					}
				});

		AlertDialog alertDialog = dialogBuilder.create();
		alertDialog.show();
	}

	/* Dialog box for confirmation for deleting an account */
	private void showDialogBoxDeleteAccount(String title, String message) {
		/* Firstly we create an object of AlertDialog.Builder */
		AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
		/* Now we initialise its contents */
		dialogBuilder.setTitle(title);
		dialogBuilder.setMessage(message);
		dialogBuilder.setPositiveButton("Yes",
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						/* Code to open the database */
						databaseOperations.openWriteableDatabase();

						/* Pop up for showing that account deleted */
						Toast.makeText(
								getApplicationContext(),
								"Account "
										+ ChooseAccount2_ListViewAdapter
												.getTextOfSelectedTextview()
										+ " has been deleted",
								Toast.LENGTH_SHORT).show();

						/**************************************************/
						/* Need to delete for tme uniquetablenames too */
						ArrayList<String> arrayList = databaseOperations.retrieveAll(
								DatabaseOperations_NonActivity.getMembertable(),
								new String[] { DatabaseOperations_NonActivity
										.getMembertablemember() },
								DatabaseOperations_NonActivity
										.getMembertabletitle()
										+ "='"
										+ ChooseAccount2_ListViewAdapter
												.getTextOfSelectedTextview()
										+ "'", null, null, null, null);
						for (String str : arrayList) {
							databaseOperations.deleteRow(
									DatabaseOperations_NonActivity
											.getUniquenamestable(),
									DatabaseOperations_NonActivity
											.getUniquenamestablenames()
											+ "=\""
											+ str + "\"", null);

						}
						/**************************************************/
						@SuppressWarnings("unused")
						int x = databaseOperations.deleteRow(
								DatabaseOperations_NonActivity.getAmounttable(),
								DatabaseOperations_NonActivity
										.getAmounttabletitle()
										+ "="
										+ "\""
										+ ChooseAccount2_ListViewAdapter
												.getTextOfSelectedTextview()
										+ "\"", null);

						/* Code to get all the accounts from the database */
						titles = databaseOperations.retrieveAll(
								DatabaseOperations_NonActivity.getAmounttable(),
								new String[] { DatabaseOperations_NonActivity
										.getAmounttabletitle() }, null, null,
								null, null, null);

						/* Initializing the adapter */
						listViewAdapterForChooseAccount2 = new ChooseAccount2_ListViewAdapter(
								ChooseAccount2.this, titles);
						listViewForShowingAccountNames
								.setAdapter(listViewAdapterForChooseAccount2);
						ChooseAccount2_ListViewAdapter
								.setTextOfSelectedTextview(null);
						if (titles.size() == 0) {
							Toast.makeText(getApplicationContext(),
									"No Account to open", Toast.LENGTH_SHORT)
									.show();
							/* Code to close the database */
							databaseOperations.closeDatabase();
							finish();
							return;
						}

						/* Code to close the database */
						databaseOperations.closeDatabase();
					}
				});

		dialogBuilder.setNegativeButton("No",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						return;
					}
				});

		AlertDialog alertDialog = dialogBuilder.create();
		alertDialog.show();
	}

	/* A function to check whether the account was selected or not */
	private boolean checkIfAnyAccountHasBeenSelectedOrNot() {
		if (ChooseAccount2_ListViewAdapter.getTextOfSelectedTextview() == null) {
			Toast.makeText(getApplicationContext(), "No Account Selected",
					Toast.LENGTH_SHORT).show();
			return true;
		}
		return false;
	}

	public void addANewPurposeTextView() {
		/* Check for the account being selected or not */
		if (checkIfAnyAccountHasBeenSelectedOrNot()) {
			return;
		}
		/*
		 * Check for if the database does not exist go directly go to front
		 * screen
		 */
		if (Utils_NotActivity.databaseDoesNotExist(getApplicationContext())) {
			Intent intent1 = new Intent(ChooseAccount2.this, FrontScreen.class);
			startActivity(intent1);
			return;
		}

		SessionClass_NonActivity.sessionObject().setTitle(
				ChooseAccount2_ListViewAdapter.getTextOfSelectedTextview());
		Intent intent = new Intent(ChooseAccount2.this, Purpose2.class);
		startActivity(intent);
	}

	public void editAccountTextView() {
		/* Check for the account being selected or not */
		if (checkIfAnyAccountHasBeenSelectedOrNot()) {
			return;
		}
		/*
		 * Check for if the database does not exist go directly go to front
		 * screen
		 */
		if (Utils_NotActivity.databaseDoesNotExist(getApplicationContext())) {
			Intent intent1 = new Intent(ChooseAccount2.this, FrontScreen.class);
			startActivity(intent1);
			return;
		}

		/* Setting the session */
		SessionClass_NonActivity.sessionObject().setTitle(
				ChooseAccount2_ListViewAdapter.getTextOfSelectedTextview());
		/* Creating the intent to go to another activity */
		Intent intent = new Intent(ChooseAccount2.this, EditAccount2.class);
		startActivity(intent);
	}

	public void deleteAccountTextview() {
		/* Check for the account being selected or not */
		if (checkIfAnyAccountHasBeenSelectedOrNot()) {
			return;
		}
		/*
		 * Check for if the database does not exist go directly go to front
		 * screen
		 */
		if (Utils_NotActivity.databaseDoesNotExist(getApplicationContext())) {
			Intent intent1 = new Intent(ChooseAccount2.this, FrontScreen.class);
			startActivity(intent1);
			return;
		}

		showDialogBoxDeleteAccount(
				"Delete Account",
				"Do you want to delete the "
						+ ChooseAccount2_ListViewAdapter
								.getTextOfSelectedTextview() + " Account?");
	}

	public void openStatisticsTextview() {
		/* Check for the account being selected or not */
		if (checkIfAnyAccountHasBeenSelectedOrNot()) {
			return;
		}
		/*
		 * Check for if the database does not exist go directly go to front
		 * screen
		 */
		if (Utils_NotActivity.databaseDoesNotExist(getApplicationContext())) {
			Intent intent1 = new Intent(ChooseAccount2.this, FrontScreen.class);
			startActivity(intent1);
			return;
		}

		SessionClass_NonActivity.sessionObject().setTitle(
				ChooseAccount2_ListViewAdapter.getTextOfSelectedTextview());
		Intent intent = new Intent(ChooseAccount2.this,
				OpenAccountStatistics.class);
		startActivity(intent);
	}

	public void renameAccountTextview() {
		/* Check for the account being selected or not */
		if (checkIfAnyAccountHasBeenSelectedOrNot()) {
			return;
		}
		/*
		 * Check for if the database does not exist go directly go to front
		 * screen
		 */
		if (Utils_NotActivity.databaseDoesNotExist(getApplicationContext())) {
			Intent intent1 = new Intent(ChooseAccount2.this, FrontScreen.class);
			startActivity(intent1);
			return;
		}

		showDialogBoxRenameAccount("Rename the Account",
				"Enter the account name");
	}
}
